<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/29
 * Time: 11:14
 */

namespace App\Http\Controllers\Api\V3;

use App\Common\ApiData;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
use App\Modules\EntBookInfo;
use App\Modules\EntBookImg;
use App\Modules\EntMemberInfo;
use App\Modules\EntBookSumUp;
use App\Modules\EntBookCollect;
use App\Modules\EntBookViewLog;
use Validator, DB;
//use phpmailerException;
use PHPMailer;


use App\Models\V1\BookModel;
use App\Models\V1\MemberModel;

class BookController extends BaseController
{
    protected $url;

    public function __construct()
    {
        $this->url = env('ADMIN_HOST');
    }

    /**
     * 书籍分类
     *
     */
    public function getBookType()
    {
        $bookModel = new BookModel();
        $bookTypes = $bookModel->get_book_types();
        $data      = ['message' => 'ok', 'code' => '200', 'booktypelist' => $bookTypes];
        return response()->json($data);
    }


    /**
     * 广告
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookHotsList()
    {
        $bookModel = new BookModel();
        $hotBooks  = $bookModel->get_hot_books();
        return response()->json(['message' => 'ok', 'code' => '200', 'hotslist' => $hotBooks]);
    }


    /**
     * 推荐书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookRecommendList()
    {
        $bookModel      = new BookModel();
        $recommentBooks = $bookModel->get_recomment_books();
        return response()->json(['message' => 'ok', 'code' => '200', 'bookrecommendlist' => $recommentBooks]);
    }


    /**
     * 添加读书改进计划
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bookSumUpStore(Request $request)
    {
        $result   = 'no';
        $rules    = [
            'mobile'    => 'required',
            'id'        => 'required',
            'key'       => 'required',
            'upid'      => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages = [
            'mobile.required'    => '2019',
            'id.required'        => '2020',
            'key.required'       => '2021',
            'upid.required'      => '2036',
            'timestamp.required' => '2026',
            'sign.required'      => '2027'
        ];


        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $id        = $request->input('id');
        $upid      = $request->input('upid');
        $bookidea1 = $request->input('bookidea1');
        $bookidea2 = $request->input('bookidea2');
        $bookidea3 = $request->input('bookidea3');
        $bookidea4 = $request->input('bookidea4');
        $timestamp = $request->input('timestamp');
        $sign      = $request->input('sign');

        $params = [
            'mobile'    => $mobile,
            'key'       => $key,
            'id'        => $id,
            'upid'      => $upid,
            'bookidea1' => $bookidea1,
            'bookidea2' => $bookidea2,
            'bookidea3' => $bookidea3,
            'bookidea4' => $bookidea4,
            'timestamp' => $timestamp,
            'sign'      => $sign
        ];


        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        $bookidea1 = emoji_text_encode($bookidea1);
        $bookidea2 = emoji_text_encode($bookidea2);
        $bookidea3 = emoji_text_encode($bookidea3);
        $bookidea4 = emoji_text_encode($bookidea4);

        /*
         if ($this->checkSign($params) != true) {
            return response()->json(['message' => "签名失败", 'code' => '3019']);
        }
        */


        $memNumber = $this->memNumber($mobile, $key);

        if (count($memNumber) == 0) {
            return response()->json(['message' => "用户不存在", 'code' => '3020']);
        }


        if ($upid == 0) {
            $sumpInfo = DB::table('booksumup')
                ->where('BookID', $id)
                ->where('MemNumber', $memNumber->MemNumber)
                ->orderBy('SumUpID', 'DESC')
                ->first();
            if ($sumpInfo) {
                $upid = $sumpInfo->SumUpID;
            }
        }


        if ($upid == 0) {   //验证是否已经添加过
//            $entBookSumUp              = new EntBookSumUp();
//            $entBookSumUp->BookID      = $id;
//            $entBookSumUp->MemNumber   = $memNumber->MemNumber;
//            $entBookSumUp->BookReview1 = $bookidea1;
//            $entBookSumUp->BookReview2 = $bookidea2;
//            $entBookSumUp->BookReview3 = $bookidea3;
//            $entBookSumUp->BookReview4 = $bookidea4;
//            $entBookSumUp->AddDate     = date('Y-m-d H:i:s', time());
//            $entBookSumUp->save();

            $entBookSumUp = EntBookSumUp::firstOrCreate(
                [
                    'BookID'    => $id,
                    'MemNumber' => $memNumber->MemNumber
                ],
                [
                    'BookID'      => $id,
                    'MemNumber'   => $memNumber->MemNumber,
                    'BookReview1' => $bookidea1,
                    'BookReview2' => $bookidea2,
                    'BookReview3' => $bookidea3,
                    'BookReview4' => $bookidea4,
                    'AddDate'     => date('Y-m-d H:i:s', time()),
                ]
            );
        } else {    //验证是否已经添加过
            $entBookSumUp              = EntBookSumUp::find($upid);
            $entBookSumUp->BookReview1 = $bookidea1;
            $entBookSumUp->BookReview2 = $bookidea2;
            $entBookSumUp->BookReview3 = $bookidea3;
            $entBookSumUp->BookReview4 = $bookidea4;
            $entBookSumUp->AddDate     = date('Y-m-d H:i:s', time());
            $entBookSumUp->save();
        }

        if ($entBookSumUp) {
            return response()->json(['message' => '保存成功', 'code' => '200']);
        } else {
            return response()->json(['message' => "保存失败", 'code' => '3021']);
        }
    }

    /**
     * 收藏书籍
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bookCollectStore(Request $request)
    {
        $result    = 'no';
        $rules     = [
            'mobile'    => 'required',
            'id'        => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages  = [
            'mobile.required'    => '2031',
            'id.required'        => '2032',
            'key.required'       => '2033',
            'timestamp.required' => '2034',
            'sign.required'      => '2035'
        ];
        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $id        = $request->input('id');
        $timestamp = $request->input('timestamp');
        $sign      = $request->input('sign');
        $params    = ['mobile' => $mobile, 'key' => $key, 'id' => $id, 'timestamp' => $timestamp, 'sign' => $sign];
        $v         = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => '3026']);
        }

        $memNumber = $this->memNumber($mobile, $key);
        if (count($memNumber) == 0) {
            return response()->json(['message' => $result, 'code' => '3025']);
        }

        $entBookInfo = EntBookInfo::where('BookID', $id)->where('DeleteMark', '1')->first();
        if (count($entBookInfo) > 0) {
            $entBookCollect = EntBookCollect::select('ColID')
                ->where('MemNumber', $memNumber->MemNumber)
                ->where('BookID', $id)
                ->first();

            if (count($entBookCollect) == 0) {
                $BookCollectStore            = new EntBookCollect();
                $BookCollectStore->BookID    = $id;
                $BookCollectStore->MemNumber = $memNumber->MemNumber;
                $BookCollectStore->AddDate   = date('Y-m-d H:i:s', time());
                $BookCollectStore->save();
                if ($BookCollectStore) {
                    return response()->json(['message' => 'ok', 'code' => '200']);
                } else {
                    return response()->json(['message' => $result, 'code' => '3022']);
                }
            } else {
                EntBookCollect::destroy($entBookCollect->ColID);
                return response()->json(['message' => 'ok', 'code' => '200']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3024']);
        }

    }

    /**
     * 返回会员标示
     * @param string $mobile
     * @param string $appkey
     * @return mixed
     */
    protected function memNumber($mobile = '', $appkey = '')
    {
        $entBookInfo = EntMemberInfo::select('UserID', 'MemNumber', 'MemEndTime', 'States', 'YourName')
            ->where('DeleteMark', '1')
            ->where('AppKey', $appkey)
            ->where('UserName', $mobile)
            ->first();
        return $entBookInfo;
    }



    /**========Ron重新编码==========*/


    /**
     * 书籍详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getbookdetail(Request $request)
    {
        $result = "no";

        $rules    = [
            'id' => 'required',
        ];
        $messages = [
            'id.required' => '2029',
        ];

        $id     = $request->input('id');
        $mobile = $request->input('mobile', 0);
        $key    = $request->input('key', 0);

        //获取书籍详细
        $entBookInfo = EntBookInfo::findOrFail($id);
        if (strtotime($entBookInfo->publish_date) == 0) {
            $entBookInfo->publish_date = substr($entBookInfo->AddDate, 0, 10);
        }
        if (count($entBookInfo) > 0) {
            $entBookInfo->FilePath1 = $this->url . $entBookInfo->FilePath1;
            $entBookInfo->FilePath2 = $entBookInfo->mp4;
            $entBookInfo->FilePath3 = $entBookInfo->mp3;
        }

        //获取PPT
        $entBookImg = EntBookImg::select('FilePath1', 'SortNumber')
            ->where('BookID', $id)
            ->orderBy('SortNumber', 'asc')
            ->orderBy('AddDate', 'asc')
            ->get();

        if (count($entBookImg) > 0) {
            foreach ($entBookImg as $imgkey) {
                $imgkey->FilePath1 = $this->url . $imgkey->FilePath1;
            }
        }


        if ($mobile && $key) {
            $params = ['mobile' => $mobile, 'key' => $key, 'id' => $id];
            $v      = Validator::make($params, $rules, $messages);
            if ($v->fails()) {
                return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
            }

            //书籍读书改进计划
            $memNumber = $this->memNumber($mobile, $key);

            if (count($memNumber) == 0) {
                //throw new \Exception("用户不存在", '400');
                $data = ['error_code' => "400", 'error_info' => "请重新登录"];
                return $data;
            }

            //会员是否到期
            $nowtime = date('Y-m-d h:i:s', time());
            $endtime = $memNumber->MemEndTime;
            if (strtotime($nowtime) > strtotime($endtime)) {
                $i = 1;//会员到期
            } else {
                $i = 2; //已付费
            }
            //书籍收藏 0--未收藏 1--已收藏
            $isCollect      = '0';
            $entBookCollect = EntBookCollect::select('ColID')->where('MemNumber', $memNumber->MemNumber)->where('BookID', $id)->get();
            if (count($entBookCollect) > 0) {
                $isCollect = '1';
            }

            //改进计划
            $entBookSumUp = EntBookSumUp::select('SumUpID', 'BookReview1', 'BookReview2', 'BookReview3', 'BookReview4')
                ->where('BookID', $id)
                ->where('MemNumber', $memNumber->MemNumber)
                ->orderBy('SumUpID', 'desc')
                ->first();
            if (count($entBookSumUp) == 0) {
                $entBookSumUp              = new \stdClass();
                $entBookSumUp->SumUpID     = 0;
                $entBookSumUp->BookReview1 = '';
                $entBookSumUp->BookReview2 = '';
                $entBookSumUp->BookReview3 = '';
                $entBookSumUp->BookReview4 = '';
            } else {
                $entBookSumUp->BookReview1 = emoji_text_decode($entBookSumUp->BookReview1);
                $entBookSumUp->BookReview2 = emoji_text_decode($entBookSumUp->BookReview2);
                $entBookSumUp->BookReview3 = emoji_text_decode($entBookSumUp->BookReview3);
                $entBookSumUp->BookReview4 = emoji_text_decode($entBookSumUp->BookReview4);
            }

            //观看记录
            $checkBookViewLog = EntBookViewLog::select('ViewLogID')
                ->where('BookID', $id)
                ->where('MemNumber', $memNumber->MemNumber)
                ->get();

            if (count($checkBookViewLog) == 0) {
                $entBookViewLog            = new EntBookViewLog();
                $entBookViewLog->BookID    = $id;
                $entBookViewLog->MemNumber = $memNumber->MemNumber;
                $entBookViewLog->FilePath1 = $entBookInfo->FilePath1;
                $entBookViewLog->StartTime = date('Y-m-d H:i:s', time());
                $entBookViewLog->EndTime   = '';
                $entBookViewLog->AddDate   = date('Y-m-d H:i:s', time());
                $entBookViewLog->save();
            }

//            $data['data']['imglist'] = $entBookImg;
//            $data['data']['sumuplist'] = $entBookSumUp;
//            $data['data']['isCollect'] = $isCollect;

            if ($memNumber->States == 1) {
                $nowtime = date('Y-m-d h:i:s', time());
                $endtime = $memNumber->MemEndTime;
                if (strtotime($nowtime) > strtotime($endtime)) {
                    $memstate = 1;//会员到期
                } else {
                    $memstate = 2; //已付费
                }
            } else {
                $memstate = 4;//未付费
            }

        } else {
            $isCollect    = "";
            $memstate     = 3;
            $entBookSumUp = "";
        }

        //更新书籍查看数
        DB::table('BookInfo')->where('BookID', $entBookInfo->BookID)->increment('ReadNumber');
        $entBookInfo->isCollect = $isCollect;
        //return $entBookSumUp;
        $readPlanId = $entBookSumUp ? $entBookSumUp->SumUpID : 0;

        $pas = [
            'readPlanId=' . $readPlanId,
            'bookId=' . $entBookInfo->BookID,
            'userId=' . $memNumber->UserID
        ];

        $pas = implode('&', $pas);

        $shareInfo = [
            'title'       => $memNumber->YourName . "读《" . $entBookInfo->BookTitle . "》的改进计划",
            'description' => $entBookSumUp->BookReview1,
            'img'         => $entBookInfo->FilePath1,
            'link'        => env('ADMIN_HOST') . "/home/share_read_plan?" . $pas,
            'groupTitle'  => $memNumber->YourName . "读《" . $entBookInfo->BookTitle . "》的改进计划\n老侯论道"
        ];


        $data = [
            'error_code' => "200",
            'error_info' => "ok",
            'data'       => [
                'imglist'    => $entBookImg,
                'bookdetail' => $entBookInfo,
                'memstate'   => $memstate,
                'sumuplist'  => $entBookSumUp,
                'isCollect'  => $isCollect,
                'shareInfo'  => $shareInfo
            ]
        ];
        return $data;
    }


    /**
     * 所有书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookList(Request $request)
    {
        $mobile       = $request->input('mobile', 0);
        $key          = $request->input('key', 0);
        $friendUserId = $request->input('friendUserId', 0);

        //读取所有书籍
        $bookModel      = new BookModel();
        $entBookInfo    = $bookModel->get_book_list(0,true,'lhdd');

        foreach ($entBookInfo as $book) {
            $book->hasReadPlan = 0;
        }

        define('mem_status_unlogin', 3);
        define('mem_status_had_end', 1);
        define('mem_status_payed', 2);
        define('mem_status_unpay', 4);
        $memStatus = mem_status_unlogin;


        $entMemberInfo = false;
        $memberModel   = new MemberModel();
        if ($mobile && $key) {
            $entMemberInfo = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        }

        if ($entMemberInfo) {
            $memTime   = $entMemberInfo->AddDate;
            $memNumber = $entMemberInfo->MemNumber;


            //取出该会员所有收藏的书籍
            $collectedBook = $bookModel->get_member_collected_book($memNumber);
            $colllist      = [];
            foreach ($collectedBook as $book) {
                array_push($colllist, $book->BookID);
            }


            $readPlanUserMember = $memNumber; //好友的读书改进  如果没有好友 则是自己
            if ($friendUserId > 0) {
                $friendInfo         = $memberModel->get_member_info_by_id($friendUserId);
                $readPlanUserMember = $friendInfo->MemNumber;
            }

            //取出已经填写过读书计划的书籍
            $hasWriteReadPlan = DB::table('booksumup')
                ->where('MemNumber', $readPlanUserMember)
                ->distinct()
                ->pluck('BookID')
                ->toArray();
            $hasWriteReadPlan = $hasWriteReadPlan ? $hasWriteReadPlan : [];

            //程序调整书籍排列顺序0不显示 1显示
            foreach ($entBookInfo as $book) {
                $bookAddTime   = $book->AddDate;
                $memberAddTime = $memTime;
                if (strtotime($bookAddTime) > strtotime($memberAddTime)) {
                    $book->IsShow = 0;
                }

                //是否收藏过该书籍 0-否 1-是--MasterID
                $bookId            = $book->BookID;
                $book->MasterID    = in_array($bookId, $colllist) ? 1 : 0;
                $book->hasReadPlan = in_array($bookId, $hasWriteReadPlan) ? 1 : 0;
            }


            //判断用户的状态
            if ($entMemberInfo->States == 1) {
                $nowtime = date('Y-m-d h:i:s', time());
                $endtime = $entMemberInfo->MemEndTime;
                if (strtotime($nowtime) > strtotime($endtime)) {
                    $memStatus = mem_status_had_end;//会员到期
                } else {

                    $memStatus = mem_status_payed; //已付费
                }
            } else {
                $memStatus = mem_status_unpay;//未付费
            }
        }


        if ($memStatus != mem_status_payed) {
            $isPay     = DB::table('orderprepaidlog')
                ->where('app_key', $key)
                ->where('pay_status', 1)->count();
            $memStatus = $isPay > 0 ? mem_status_payed : mem_status_unpay;
        }

        $data['error_code'] = '200';
        $data['error_info'] = '成功';
        $data['data']       = [
            'memstate' => $memStatus,
            'booklist' => $entBookInfo
        ];
        return $data;
    }


    /**
     * 发送书籍PPT
     * */
    public function send_book_ppt(Request $request)
    {

        $email     = $request->input('email');
        $bookId    = $request->input('bookId');
        $apiData   = new ApiData();
        $bookModel = new BookModel();
        $bookInfo  = $bookModel->get_book_info($bookId);
        $ppts      = $bookModel->get_book_ppt($bookId);


        $content = view('other/email-ppt', ['ppts' => $ppts, 'bookInfo' => $bookInfo]);
        //return $content;

        //Create a new PHPMailer instance
        $mail = new PHPMailer();

        //$file = public_path('uploads/ppt.zip');
        if (empty($bookInfo->ppt)) {
            return $apiData->send('2001', '本书籍暂无PPT文件');
        }
        $file = public_path('') . $bookInfo->ppt;
        $ext  = explode('.', $bookInfo->ppt);

        $mail->SMTPDebug = 0;
        $mail->IsSMTP(); // 启用SMTP
        $mail->Port = 465;
        //$mail->Host='smtp.sina.cn'; //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->Host     = 'ssl://smtp.qq.com'; //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->SMTPAuth = true; //启用smtp认证

//        $mail->Username = 'zhweixi@sina.cn'; //你的邮箱名
//        $mail->Password = 'zhangweixi123' ; //邮箱密码

        $mail->Username = '3367067598@qq.com'; //你的邮箱名
        $mail->Password = 'pqmlpzsxufhadbid'; //邮箱密码

//        $mail->From = 'zhweixi@sina.cn'; //发件人地址（也就是你的邮箱地址）
        $mail->From     = '3367067598@qq.com'; //发件人地址（也就是你的邮箱地址）
        $mail->FromName = "教导读书会"; //发件人姓名
        $mail->AddAddress($email, "尊敬的客户");
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(true); // 是否HTML格式邮件
        $mail->CharSet = 'utf-8'; //设置邮件编码
        $mail->Subject = "书籍《" . $bookInfo->BookTitle . "》PPT"; //邮件主题
        $mail->AddAttachment($file, $bookInfo->BookTitle . "PPT." . $ext[1]);
        $mail->Body    = $content; //邮件内容
        $mail->AltBody = "活动信息"; //邮件正文不支持HTML的备用显示

        $result = $mail->Send();
        //$result = true;

        //mylogger('email:'.$email.'-----'.$bookId);
        //return [$mail->ErrorInfo];

        if ($result) {
            return $apiData->send('200', 'PPT发送成功');
        } else {
            return $apiData->send("400", $mail->ErrorInfo);
        }
    }


}